﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Http;

namespace HW7_1Crawler
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource cancellationTokenSource;

        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            // 禁用搜索按钮
            button1.Enabled = false;
            // 显示“正在搜索”消息
            listBox1.Items.Add("正在搜索，请稍候...");

            // 取消上一次的搜索
            cancellationTokenSource?.Cancel();

            // 创建一个新的取消令牌源
            cancellationTokenSource = new CancellationTokenSource();

            // 获取用户输入的关键词
            string keyword = textBox1.Text.Trim();

            // 使用Bing搜索引擎进行搜索
            string url = $"https://www.bing.com/search?q={WebUtility.UrlEncode(keyword)}";

            // 创建HttpClient对象，下载搜索结果页面
            HttpClient httpClient = new HttpClient();
            string html = await httpClient.GetStringAsync(url);

            // 从页面中提取URL
            List<string> urls = ExtractUrlsFromHtml(html);

            // 显示搜索结果
            listBox1.Items.Clear();
            foreach (string u in urls)
            {
                listBox1.Items.Add(u);
            }

            // 启用搜索按钮
            button1.Enabled = true;
        }

        private List<string> ExtractUrlsFromHtml(string html)
        {
            List<string> urls = new List<string>();

            // 正则表达式匹配URL
            string pattern = @"<a\s+[^>]*href\s*=\s*(?:'(?<url>[^']*)'|""(?<url>[^""]*)""|(?<url>[^\s>]+)).*?>";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(html);
            foreach (Match match in matches)
            {
                string url = match.Groups["url"].Value;
                if (url.StartsWith("http://") || url.StartsWith("https://"))
                {
                    urls.Add(url);
                }
            }

            return urls;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void textBox2_TextChanged_1(object sender, EventArgs e)
        {
            
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 取消当前搜索
            cancellationTokenSource?.Cancel();
        }


    }
}